package com.bobo.rbac.controller;

import cn.hutool.captcha.generator.RandomGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bobo.rbac.auth.ann.LogAnn;
import com.bobo.rbac.auth.utils.JwtUtils;
import com.bobo.rbac.auth.utils.ResponseResult;
import com.bobo.rbac.domain.User;
import com.bobo.rbac.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: BOBO
 * @time: 2022/7/27 15:06
 */

@Slf4j
@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;



    /**
     * 获取用户list
     */
    @LogAnn
    @RequestMapping("list")
    public ResponseResult list(User user, Page page) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(user.getUsername()), "username", user.getUsername())
                .like(!StringUtils.isEmpty(user.getPhone()), "phone", user.getPhone());
        IPage<User> pageInfo = userService.page(page, queryWrapper);
        return ResponseResult.ok(pageInfo);
    }

    /**
     * 增加或修改
     *
     * @param user
     * @return
     */
    @LogAnn
    @RequestMapping("saveOrUpdate")
    public ResponseResult save(@RequestBody User user) {
        boolean b = userService.saveOrUpdate(user);
        if (b) {
            return ResponseResult.ok();
        }
        return ResponseResult.fail(300, "保存失败");
    }

    /**
     * 用户绑定角色
     *
     * @return
     */
    @RequestMapping("bindRole")
    public ResponseResult bindRole(@RequestBody User user) {
        userService.bindRole(user);

        return ResponseResult.ok("绑定成功");

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping("delBatch")
    public ResponseResult delBatch(Integer[] ids) {
        //  String[] s = ids.split(",");
        userService.removeByIds(Arrays.asList(ids));
        log.debug("要删除的数据是："+ids);
        return ResponseResult.ok();
    }

    // @Value("${file.uploadRealPath}")
    private String filePath = "d:/pic/";

    @RequestMapping("upFile")
    public ResponseResult upFile(MultipartFile file) throws IOException {
        if (null != file && !file.isEmpty()) {
            String oName = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + oName.substring(oName.lastIndexOf("."));
            File upFile = new File(filePath, fileName);
            file.transferTo(upFile);
            return ResponseResult.ok("/pic/" + fileName);
        }
        return ResponseResult.fail(300, "上传失败，请选择上传文件");
    }


    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 校验密码
     *
     * @param password
     * @return
     */
    @RequestMapping("checkPWD")
    public ResponseResult checkPWD(String password) {
        User user = null;
        //获取当前登录人的用户信息
        user = this.getCurrentUser();
        if (null != user) {
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            if (matches)
                return ResponseResult.ok();
        }
        return ResponseResult.fail(300, "密码输入错误");
    }

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromUser;

    @RequestMapping("changePWD")
    public ResponseResult changePWD(@RequestBody User user) {

        User user1 = this.getCurrentUser();//获取当前用户
        user1.setPassword(passwordEncoder.encode(user.getNewPassword()));//赋值新密码
        userService.saveOrUpdate(user1);
        //密码更改成功，发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("权限项目--密码变更了");
        message.setText("您的密码刚刚重新设置了，请下次是使用新密码登录");
        message.setFrom(fromUser);
        message.setTo(user1.getMail());
        javaMailSender.send(message);

        return ResponseResult.ok();
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    private User getCurrentUser() {
        String username = JwtUtils.getUsername();
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("username", username);
        User user = userService.getOne(qw);//根据用户名获取用户对象
        return user;
    }


    @RequestMapping("sendMail")
    public ResponseResult sendMail(String mail){
        //密码忘记，发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("忘记密码");
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        String code = randomGenerator.generate();
        message.setText("你的验证码是："+code+"有效期30分钟");
        message.setFrom(fromUser);
        message.setTo(mail);
        javaMailSender.send(message);
        //redis 存储一份
        redisTemplate.opsForValue().set(mail,code,30, TimeUnit.MINUTES);
      return ResponseResult.ok();
    }
}
